#include <stdio.h>
#include <math.h>
#include "wraplinux.h"
#include "dyn_arr.h"

// How many numbers in the fibonacci sequence to generate
#define FIB_MAXVAL 4000000

/* Puts a fibonacci sequence into an array pointed to by *arr */
int fibonacci(int maxval, darri *arr)
{
	int last = 2; // First last element
	int lastlast = 1; // 2nd last element
	int old_last;

	// We already know what those are, right?
	darri_put(arr, 1);
	darri_put(arr, 2);

	while ( 1 )
	{
		// save the old last as we're going to replace it now. We'll use this
		// var to set lastlast.
		old_last = last;
		last = lastlast + last;
		if ( last > maxval ) {
			break;
		}
		lastlast = old_last;

		darri_put(arr, last);
	}
	return 0;
}

int
main(int argc, char *argv[])
{
	// This array is to put a fibonacci sequence
	darri arr;
	int sum_even = 0;
	int i;

	darri_init(&arr, 1);

	fibonacci(FIB_MAXVAL, &arr);

	for ( i = 0; i < arr.pos; i++ ) {
		if( fmod(arr.arr[i], 2) == 0 ) {
			sum_even += arr.arr[i];
		}
	}

	printf("%d\n", sum_even);
	return 0;
}
